import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart


class Send_Test_Html():

    def new_report(self):
        test_report = r'F:\TJC\TestCode\QC_APP\QC_APP_TestCode2\outputs\logs'
        lists = os.listdir(test_report)  # 列出目录的下所有文件和文件夹保存到lists
        lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn))  # 按时间排序
        file_new = os.path.join(test_report, lists[-1])  # 获取最新的文件保存到file_new
        print(file_new)
        return file_new

    def smtpLib(self):
        # 发送邮件，需要第三方的smtp服务器，这里的密码是在邮箱网站申请授权码，不是自己的登录密码
        mail_user = '728821370@qq.com'
        mail_pass = 'iqdtbfeipjrnbehg'
        # 接收邮件，可设置为你的其他邮箱
        receivers = ['17316194903@139.com,728821370@qq.com']
        # 邮件内容，文本格式，把plain改成html是html格式
        message = MIMEMultipart()
        mail_msg = '青创繁星APP测试日志.log，请查询附件！'
        message.attach(MIMEText(mail_msg,'html','utf-8'))

        # 构造附件，传送当前目录下的 txt 文件
        op = open(self.new_report(),'rb').read()
        att = MIMEText(op,'base64','utf-8')
        att["Content-Type"] = 'application/octet-stream'
        # 附件名称非中文时的写法,这里的filename可以任意写，写什么名字，邮件中显示什么名字，
        # att["Content-Disposition"] = 'attachment; filename="{}"'.format('job')
        att.add_header('Content-Disposition', 'attachment', filename='青创繁星APP测试日志.log')
        message.attach(att)

        # 显示的发件人
        message['From'] = mail_user
        # 显示的收件人
        message['To'] = ','.join(receivers)
        message['Subject'] = Header('青创繁星APP测试日志', 'utf-8')

        try:
            # QQ邮箱SMTP服务器smtp.qq.com（端口465或587）SSL一般用465
            smtpObj = smtplib.SMTP_SSL('smtp.qq.com', 465)
            smtpObj.login(mail_user, mail_pass)
            smtpObj.sendmail(mail_user, message['To'].split(','), message.as_string())
            smtpObj.quit()
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")

Send_SmtpLib = Send_Test_Html()

if __name__ == '__main__':
    Fn = Send_Test_Html()
    Fn.smtpLib()